<?php

namespace app\erp\controller;

use app\admin\model\BdOrg;
use app\admin\model\Inventoryentry;
use app\admin\model\Synlogs;
use think\Log;

class Inventory extends Base
{
    public function __construct($starttime, $endtime,$client_id,$client_secret,$account_id,$user_name)
    {
        parent::__construct($client_id, $client_secret,$account_id,$user_name);

        $this->starttime = $starttime;
        $this->endtime   = $endtime;
    }
    public function run($forg_fnumber,$forig_id,$page,$pageSize,$uuid)
    {

        $res = $this->getInventoryGroupPage($forg_fnumber,$page,$pageSize,$uuid);

        if($res['code'] === 1)
        {
            $response = $this->insertDataAndUpdateSuper($res['data'], $forig_id,$uuid);

            if($response)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_successnums' => $response['total'],
                    'fk_bdl_status'      => "true",
                    'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
                ]);
                Log::info('库存成功,'. "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forg_fnumber . "参数：" . json_encode($res['data']));

                return "组织编码".$forg_fnumber . ':本次成功同步条数' . $response['total'];

            }
        }elseif ($res['code'] === 2) {
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_successnums' => 0,
                'fk_bdl_status'      => "true",
                'fk_bdl_endtime'     => date("Y-m-d H:i:s"),
            ]);
            return "组织编码".$forg_fnumber . ':本次成功同步条数0';

        }

    }


    private function getInventoryGroupPage($createorg_number, $pageNo, $pageSize,$uuid)
    {
//        if(in_array($this->account_id,[1808778350425014272,1845044874454237184]))
//        {
//            $method  = "v2/bdl/bdl_bal/bdl_bal_inventory/queryInventory";
//        }else{
//            $method = "v2/bdl/bdl_balance/bdl_inventory/queryInventory";
//        }

        $method = $this->datacenter_data['fk_bdl_queryinventory'];

        $fullurl = $this->url . $method;

        Synlogs::where('id',$uuid)->update([
            'fk_bdl_url'        => $fullurl,

        ]);
        $response_data = [
            'data'      => [
                'starttime'             => $this->starttime,
                'endtime'               => $this->endtime,
                'org_number'            => $createorg_number,
            ],
            'pageNo'    => $pageNo,
            'pageSize'  => $pageSize,
        ];



        $this->curl->setHeader("Content-Type", "application/json");
        $this->curl->setHeader("accesstoken", $this->getToken());
        $this->curl->setHeader("Idempotency-Key", uuid());

        $res = $this->curl->post($fullurl, json_encode($response_data));


        if ($res && is_object($res) && $res->status == 1)
        {
            if($res->data->totalCount > 0){

                return [
                    'data' => $res->data->rows,
                    'code'  => 1

                ];
            }else{
                return [
                    'code'  => 2,
                ];
            }

        }else{
            if(strlen($res->message) > 255)
            {
//                $res->message = substr($res->message,0,155);

                return $this->error( 'aaaaaaaa'  . request()->action() .  $res->message);

            }
            if(property_exists($res,'errorCode') && $res->errorCode == 404)
            {
                return $this->error( 'aaaaaaaa'  . request()->action() .  $res->message);
            }
            Synlogs::where('id',$uuid)->update([
                'fk_bdl_exceptionmsg'   => $res->message,
                'fk_bdl_status'         => "false",
            ]);
            Log::info('库存同步失败,' . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $createorg_number . "参数：" . json_encode($response_data));
            return [
                'data' => false,
                'code'  => 0
            ];
        }


    }

    private function insertDataAndUpdateSuper($data, $forgid,$uuid)
    {
        $count = 0;


        if(!empty($data))
        {

            try {
                $forg                       = BdOrg::get($forgid);
                $fnumbers                   = explode(",",$forg['fk_bdl_mappingorg']);
                $fk_bdl_mappingorgs_forgIds = BdOrg::whereIn('fnumber',$fnumbers)->where('fk_bdl_bd_datacenter',$forg['fk_bdl_bd_datacenter'])->column('id');

                $ids = [];
                // 组装 data 并插入
                foreach ($data as $k => $v)
                {
                    //拿到产品 并用分类去拿属性
                    $mater              = \app\admin\model\Material::where('fname',$v->bdl_bd_material_name)->where('forgid','in',$fk_bdl_mappingorgs_forgIds)->where('fk_bdl_bd_datacenter',$forg['fk_bdl_bd_datacenter'])->with(['cate'])->find();

                    $get_matprop_id     = \app\admin\model\Materialentry::where('forgid','in',$fk_bdl_mappingorgs_forgIds)->where('fk_bdl_bd_material_g',$mater['cate']['id'])->column('fk_bdl_bd_matprop');


                    // 组装数据 库存属性值
                    $tk_bdl_bal_inventoryentry = [];

                    if(!empty($get_matprop_id))
                    {
                        //排除掉bdl_bd_texture bdl_bd_surface
                        $get_matprop        = \app\admin\model\Matprop::where('id','in',$get_matprop_id)->where('fnumber','not in',['bdl_bd_texture','bdl_bd_surface'])->select();
                        if(!empty($get_matprop))
                        {
                            foreach ($get_matprop as $k1=>$v1)
                            {
                                $value = $v1['fnumber'];

                                if(isset($v->$value))
                                {
                                    $tk_bdl_bal_inventoryentry[] = [
                                        'fk_bdl_bd_datacenter'      => $forg['fk_bdl_bd_datacenter'],
                                        'forgid'                    => $forgid,
                                        'fk_bdl_matpropid'          => $v1['id'],
                                        'fk_bdl_matpropvalue'       => $v->$value
                                    ];

                                }

                            }

                        }

                    }


                    //判断是否已经存在
                    $isExist = \app\admin\model\Inventory::where('fk_bdl_keycol',$v->keycol)->where('forgid',$forgid)->where('fk_bdl_bd_datacenter',$forg['fk_bdl_bd_datacenter'])->find();
                    //拿到材质和表面id
//                    $surface = \app\admin\model\Surface::where('fnumber',$v->bdl_bd_surface_number)->where('forgid','in',$fk_bdl_mappingorgs_forgIds)->where('fk_bdl_bd_datacenter',$forg['fk_bdl_bd_datacenter'])->find();


                    $insertData = [
                        'fk_bdl_keycol'                         => $v->keycol,
                        'fk_bdl_bd_stock'                       => !empty($v->bdl_bd_stock_name) ? $v->bdl_bd_stock_name : '',
                        'forgid'                                => $forgid,
                        'fk_bdl_bd_datacenter'                  => $forg['fk_bdl_bd_datacenter'],
                        'fk_bdl_modifytime'                     => $v->modifytime,

                        'fk_bdl_bd_materialnum'                    => !empty($mater['fnumber']) ? $mater['fnumber'] : $v->bdl_bd_material_number ,
                        'fk_bdl_bd_texturenum'                     => $v->bdl_bd_texture_number,
                        'fk_bdl_bd_surfacenum'                     => $v->bdl_bd_surface_number,

                        'fk_bdl_ownertype'                      => $v->bdl_ownertype,
                        'fk_bdl_owner'                          => $v->bdl_owner_name,
                        'fk_bdl_ownernum'                       => $v->bdl_owner_number,
                        'fk_bdl_priceqty'                       => $v->bdl_priceqty,
                        'fk_bdl_qty'                            => $v->bdl_qty,
                        'fk_bdl_owndepartment'                  => !empty($v->bdl_owndepartment_name) ? $v->bdl_owndepartment_name : '',
                        'fk_bdl_instockdate'                    => $v->bdl_instockdate,
//                        'fk_bdl_usableqty'                      => $v->bdl_usableqty,
                        'fk_bdl_unitid'                         => $v->bdl_unitid_name,
                        'fk_bdl_priceunitid'                    => $v->bdl_priceunitid_name,
                        'fk_bdl_bd_lot'                         => $v->bdl_bd_lot_number,
                        'fk_bdl_weightway'                      => $v->bdl_weightway_title,
                        'fk_bdl_bd_warehouse'                   => !empty($v->bdl_bd_warehouse_name) ? $v->bdl_bd_warehouse_name : '',
                        'fk_bdl_bd_contract'                    => $v->bdl_contract,
                        'fk_bdl_bd_project'                     => !empty($v->bdl_bd_project_name) ? $v->bdl_bd_project_name : '',
                        'fk_bdl_subprojectno'                   => !empty($v->bdl_subprojectno_name) ? $v->bdl_subprojectno_name : '',
                        'fk_bdl_bd_supplier'                    => !empty($v->bdl_bd_supplier_name) ? $v->bdl_bd_supplier_name : '',
                        'fk_bdl_inventoryjsondata'              => json_encode($tk_bdl_bal_inventoryentry)
                    ];
                    property_exists($v,'bdl_issystem')                    ?   $insertData['fk_bdl_issystem']    =       $v->bdl_issystem                                :               '';
                    property_exists($v,'bdl_usableqty')                    ?   $insertData['fk_bdl_usableqty']    =       $v->bdl_usableqty                                :               '';
                    property_exists($v,'bdl_usablepriceqty')                    ?   $insertData['fk_bdl_usablepriceqty']    =       $v->bdl_usablepriceqty                                :               '';
                    property_exists($v,'bdl_matpropjoin')                    ?   $insertData['fk_bdl_matpropjoin']    =       $v->bdl_matpropjoin                                :               '';
                    property_exists($v,'bdl_date')                    ?   $insertData['fk_bdl_date']    =       $v->bdl_date                                :               '';
                    property_exists($v,'bdl_billtype_name')                    ?   $insertData['fk_bdl_billtype']    =       $v->bdl_billtype_name                                :               '';
                    property_exists($v,'bdl_billno')                    ?   $insertData['fk_bdl_billno']    =       $v->bdl_billno                                :               '';
                    property_exists($v,'bdl_specification')                    ?   $insertData['fk_bdl_specification']    =       $v->bdl_specification                                :               '';
                    property_exists($v,'bdl_model')                    ?   $insertData['fk_bdl_model']    =       $v->bdl_model                                :               '';


                    if(!empty($isExist))
                    {
                        unset($insertData['forgid']);
                        unset($insertData['fk_bdl_bd_datacenter']);
                        \app\admin\model\Inventory::where('id',$isExist['id'])->update($insertData);
//                        $ids[] = $isExist['id'];
                    }else{

                        $res = \app\admin\model\Inventory::create($insertData);
//                        $ids[] = $res->id;
                    }
                    $count++;

                }

                // 插入成功后 更新 关联表
//                $this->updateinventoryentryCategory($forgid,$ids);
            }catch (\Exception $e)
            {
                Synlogs::where('id',$uuid)->update([
                    'fk_bdl_exceptionmsg' => $e->getMessage(),
                    'fk_bdl_status'         => "false",
                ]);

                Log::error('库存同步失败,'. $e->getMessage() . "时间：".date('Y-m-d H:i:s') . "组织编码："  . $forgid . "参数：" . json_encode($data));

                $this->error( 'aaaaaaaa'  . request()->action() .  $e->getMessage());


            }


        }

        return [
            'code'      =>1,
            'total'     => $count,
        ];
    }

//    public function updateinventoryentryCategory($forgid,$ids)
//    {
//        $data = \app\admin\model\Inventory::where('forgid', $forgid)
//            ->where('fk_bdl_bd_datacenter', $forg['fk_bdl_bd_datacenter'])
//            ->where('id', 'in', $ids)
//            ->whereNotNull('fk_bdl_inventoryjsondata')
//            ->chunk(100,function($data){
//                foreach ($data as $k => $v)
//                {
//                    if(!empty($v['fk_bdl_inventoryjsondata']))
//                    {
//                        $tk_bdl_bal_inventoryentry = json_decode($v['fk_bdl_inventoryjsondata'],true);
//
//                        if(!empty($tk_bdl_bal_inventoryentry))
//                        {
//                            foreach ($tk_bdl_bal_inventoryentry as $key => $value)
//                            {
//                                if(!empty($value))
//                                {
//                                    $isExist = \app\admin\model\Inventoryentry::where('id', $v['id'])
//                                        ->where('forgid', $value['forgid'])
//                                        ->where('fk_bdl_bd_datacenter', $forg['fk_bdl_bd_datacenter'])
//                                        ->where('fk_bdl_matpropid', $value['fk_bdl_matpropid'])
//                                        ->find();
//
//                                    $insertData = [
//                                        'fk_bdl_bd_datacenter'      => $value['fk_bdl_bd_datacenter'],
//                                        'forgid'                    => $value['forgid'],
//                                        'fk_bdl_matpropid'          => $value['fk_bdl_matpropid'],
//                                        'fk_bdl_matpropvalue'       => floatval($value['fk_bdl_matpropvalue']),
//                                        'id'                        => $v['id']
//                                    ];
//
//                                    if(!empty($isExist))
//                                    {
//                                        unset($insertData['id']);
//                                        Inventoryentry::where('fentryid', $isExist['fentryid'])->update($insertData);
//                                    }else{
//
//                                        Inventoryentry::create($insertData);
//                                    }
//                                }
//                            }
//                        }
//                    }
//
//                }
//
//            });
//
//
//
//    }


}